package com.jspx.txweb.view;


import com.jspx.cache.CacheManager;
import com.jspx.cache.JSCacheManager;
import com.jspx.json.JSONException;
import com.jspx.network.http.HttpClient;
import com.jspx.network.http.HttpClientFactory;
import com.jspx.security.utils.EncryptUtil;
import com.jspx.sioc.factory.LifecycleManager;
import com.jspx.txweb.annotation.HttpMethod;
import com.jspx.txweb.annotation.Safety;
import com.jspx.txweb.support.ActionSupport;
import com.jspx.utils.StringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Created by Administrator on 2017/3/19.
 * 这里并不是实时的，会有延时来确保速度
 */
@HttpMethod(caption = "WEB反向载入")
public class WebDataLoadView extends ActionSupport {
    final private static Logger log = LoggerFactory.getLogger(LifecycleManager.class);
    public static final String cacheName = "generalCache";
    final private static CacheManager cacheManager = JSCacheManager.getCacheManager();
    private String url = "http://www.weather.com.cn/data/cityinfo/101260101.html";

    public String getUrl() {
        return url;
    }

    @Safety(length=300)
    public void setUrl(String url) {
        this.url = url;
    }

    public String getHtml() throws JSONException {
        if (StringUtil.isNULL(url)) return StringUtil.empty;
        String key = EncryptUtil.getMd5(url);
        String data =  (String) JSCacheManager.get(cacheName,key);
        if (StringUtil.hasLength(data)) return data;
        data = getValue();
        JSCacheManager.put(cacheName,key,data);
        return data;
    }


    private String getValue()  {
        try {
            HttpClient httpClient = HttpClientFactory.createHttpClient(url);
            return httpClient.getString(url);
        } catch (Exception e) {
            log.info("反向载入失败:"+url,e);
            return StringUtil.empty;
        }
    }
}